package com.wjk.interceptor;

import com.wjk.pojo.Permission;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;
import java.util.Map;
import java.util.Properties;

/**
 * @author: RobertWei
 * time: 2021/8/12    16:02
 * @TODO:
 */

public class PermissionInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        //1.获取目标访问的资源
        String targetUrl = request.getRequestURI();

        //2.匿名资源校验

        Properties anonymity = (Properties) request.getServletContext().getAttribute("anonymity");

        if (anonymity.contains(targetUrl)){
            //值要是匿名资源, 授权结束放行
            return true;
        }

        //3.认证资源校验

        Properties authentication = (Properties) request.getServletContext().getAttribute("authentication");

        Map<String,Object> data = (Map<String, Object>) request.getSession().getAttribute("data");

        //到此处只有认证和授权资源, 都要求认证通过

        if (data == null) {
            //提示认证页面
            response.sendRedirect("/user/unauthentication");
            return false;
        }

        if (authentication.contains(targetUrl)){
            //是认证资源,并且认证通过
            return true;
        }


        //4.授权资源校验
        List<Permission> permissions = (List<Permission>) data.get("permissions");

        int flag = 0;

        for (Permission permission : permissions) {
            if (permission.getpUrl().equalsIgnoreCase(targetUrl)) {
                flag = 1;
                break;
            }
        }

        if (flag == 0) {
            request.getSession().setAttribute("targeUrl",targetUrl);
            response.sendRedirect("/user/unauthorization");
            return false;
        }

        return true;
    }


}
